var swig = require('swig-templates');
var swigDefaults = module.exports.swigDefaults = {
    /**
     * 查找球队
     */
    querTame: function (arr) {
        if (arr == undefined) {
            arr = ['', '', '', '/img/base/icon_team_80x80.png']
        } else {
            if (arr[3].indexOf('http:') < 0) {
                arr[3] = arr[3];
            }
        }
        return arr;
    },
    /**
     * 转换比赛时间
     */
    generateTime: function (date) {
        date = date.code;
        var dateArr = {
            mins: '',
            secs: ''
        };
        if (date == undefined) {
            return dateArr;
        }
        var tmr_ticking = parseInt(date[0]),
            countdown = parseInt(date[1]),
            tmr_updated = parseInt(date[2]) * 1000,
            tmr_mins = parseInt(date[3]),
            tmr_secs = parseInt(date[4]),
            now = new Date().getTime(),
            delta_time = (tmr_updated ? now - tmr_updated : 0),
            pass_time = tmr_mins * 60 * 1000 + tmr_secs * 1000;

        if (pass_time < 0) {
            pass_time = -1;
        }
        var n = (!tmr_ticking ? pass_time : (countdown ? pass_time - delta_time : pass_time + delta_time));

        dateArr.mins = n / 60000 >> 0;
        dateArr.secs = (n - dateArr.mins * 60000) / 1000 >> 0;

        dateArr.mins = dateArr.mins < 10 && dateArr.mins >= 0 ? '0' + dateArr.mins : dateArr.mins;
        dateArr.secs = dateArr.secs < 10 && dateArr.secs >= 0 ? '0' + dateArr.secs : dateArr.secs;
        return dateArr;
    },
    /**
     * 判断非空
     */
    verifyNull: function (val) {
        var state = true;
        if (val === undefined || val === null || val === '' || (typeof(val) == 'object' && val.length == 0)) {
            state = false;
        }
        return state;
    },
    /**
     * 截取小数点后 N 位
     */
    toFixeds: function (val, leng) {
        return !isNaN(val) ? parseFloat(val.toFixed(leng)) : 0;
    },
    /**
     * 日期自动补位
     */
    dateSeats: function (str) {
        if (str >= 0 && str < 10) {
            str = "0" + str;
        }
        return str;
    },
    /**
     * 字符串转日期
     */
    toDate: function (date) {
        date = new Date(date);
        var me = swigDefaults;
        return {
            date: date,
            year: date.getFullYear(),
            month: me.dateSeats(date.getMonth() + 1),
            day: me.dateSeats(date.getDate()),
            hours: me.dateSeats(date.getHours()),
            minutes: me.dateSeats(date.getMinutes()),
            weeks: COMMONSTATIC.WEEKS[date.getDay()],
            zoomDate: new Date(date).setHours(0, 0, 0, 0)
        }
    },
    toString: function (val) {
        val = val == undefined ? '' : val;
        return val.toString();
    },
    /**
     * 获取地址单个参数值
     * */
    getQueryValue: function (str, name) {
        var reg = new RegExp("(^|&|\\?|#)" + name + "=([^&]*)(&|\x24)", "");
        var match = str.match(reg);
        return (match) ? match[2] : '';
    },
    /**
     * 获取地址参数转数组
     * */
    getQueryJson: function (str) {
        if (str.indexOf('?') < 0) return {};
        var query = str.substr(str.indexOf('?') + 1);
        if (!query) return {};
        var params = query.split('&'),
            len = params.length,
            result = {},
            key,
            value,
            item,
            param;
        for (var i = 0; i < len; i++) {
            param = params[i].split('=');
            key = param[0];
            value = param[1];
            item = result[key];
            if ('undefined' == typeof item) {
                result[key] = value || '';
            } else if (Object.prototype.toString.call(item) == '[object Array]') {
                item.push(value);
            } else {
                result[key] = [item, value];
            }
        }
        return result;
    },
    isToday: function (star, end) {
        if (new Date(star).setHours(0, 0, 0, 0) == new Date(end).setHours(0, 0, 0, 0)) {
            return true;
        } else {
            return false;
        }
    },
    /**
     * 字符串转日期
     */
    strforDate: function (str) {
        if (str.length != 8) {
            console.error('格式不正确：如19900101');
            return new Date();
        } else {
            return new Date(str.slice(0, 4) + "/" + str.slice(4, 6) + "/" + str.slice(6, 8));
        }
    },
    /**
     * 输出8位日期
     */
    outputDate: function (date) {
        var date = new Date(date);
        if (date == NaN) {
            console.error('传参格式不正确，必须是日期格式');
            date = new Date();
        }
        var month = date.getMonth() + 1,
            day = date.getDate();
        month = month < 10 ? "0" + month : month;
        day = day < 10 ? "0" + day : day;
        return date.getFullYear() + '' + month + '' + day;
    },
    /**
     * 统计转百分比
     */
    statisticalToBar: function (star, end) {
        var bs = 100 / (parseFloat(star) + parseFloat(end));
        bs = (bs == 'Infinity' ? 0 : bs );

        var bsStar = bs == 0 ? 50 : bs * star,
            bsEnd = bs == 0 ? 50 : bs * end;
        return [bsStar, bsEnd, bs];
    },
    /**
     * 赛选篮球比赛状态--严格
     * */
    querBktRaceTrim: function (val) {
        if (val == 1 || val == 10 || val == 11 || val == 12 || val == 13 || val == 14 || val == 15 || val == 16) {
            return false;
        } else {
            return true;
        }
    },
    /**
     * 赛选篮球比赛状态
     * */
    querBktRaceTrimStrict: function (val) {
        if (val == 2 || val == 4 || val == 6 || val == 8 || val == 9) {
            return true;
        } else {
            return false;
        }
    },
    /**
     * 赛选足球比赛状态--严格
     * */
    querFtbRaceTrim: function (val) {
        if (val == 1 || val == 8 || val == 9 || val == 10 || val == 12 || val == 13) {
            return false;
        } else {
            return true;
        }
    },
    /**
     * 赛选足球比赛状态
     * */
    querFtbRaceTrimStrict: function (val) {
        if (val == 2 || val == 4 || val == 5 || val == 6 || val == 7) {
            return true;
        } else {
            return false;
        }
    },
    /**
     * 列数字转字母. 例如： 1\2\3\4 转换为 A\B\C\D
     * @param number
     * 列索引，从1开始
     * @return
     */
    numToColNo: function (number) {
        return String.fromCharCode(64 + parseInt(number));
    },
    /**
     * 数字盘口转汉字型
     * */
    goal2GoalCn: function (goal) {
        var GoalCn = "平手,平/半,半球,半/一,一球,一/球半,球半,球半/两,两球,两/两球半,两球半,两球半/三,三球,三/三球半,三球半,三球半/四球,四球,四/四球半,四球半,四球半/五,五球,五/五球半,五球半,五球半/六,六球,六/六球半,六球半,六球半/七,七球,七/七球半,七球半,七球半/八,八球,八/八球半,八球半,八球半/九,九球,九/九球半,九球半,九球半/十,十球".split(",");
        if (goal == null || goal + "" == "")
            return "";
        else {
            if (goal > 10 || goal < -10) return goal + "球";
            if (goal >= 0)  return GoalCn[parseInt(goal * 4)];
            else return "受" + GoalCn[Math.abs(parseInt(goal * 4))];
        }
    },
    /**
     * 数字盘口转数字型
     * */
    goal2GoalNum: function (goal) {
        var GoalCn2 = ["0", "0/0.5", "0.5", "0.5/1", "1", "1/1.5", "1.5", "1.5/2", "2", "2/2.5", "2.5", "2.5/3", "3", "3/3.5", "3.5", "3.5/4", "4", "4/4.5", "4.5", "4.5/5", "5", "5/5.5", "5.5", "5.5/6", "6", "6/6.5", "6.5", "6.5/7", "7", "7/7.5", "7.5", "7.5/8", "8", "8/8.5", "8.5", "8.5/9", "9", "9/9.5", "9.5", "9.5/10", "10", "10/10.5", "10.5", "10.5/11", "11", "11/11.5", "11.5", "11.5/12", "12", "12/12.5", "12.5", "12.5/13", "13", "13/13.5", "13.5", "13.5/14", "14"];
        if (goal == null || goal + "" == "")
            return "";
        else {
            if (goal > 14) return goal + "球";
            return GoalCn2[parseInt(goal * 4)];
        }
    }
};

module.exports.array = {
    /**
     * JSON数组排序
     * arr:数组 it: item name  dt: int, char  od: asc, desc
     */
    sortby: function (arr, it, dt, od) {
        var compareValues = function (v1, v2, dt, od) {
            if (dt == 'int') {
                v1 = parseInt(v1, 10);
                v2 = parseInt(v2, 10);
            } else if (dt == 'float') {
                v1 = parseFloat(v1);
                v2 = parseFloat(v2);
            }
            var ret = 0;
            if (v1 < v2) ret = 1;
            if (v1 > v2) ret = -1;
            if (od == 'desc') {
                ret = 0 - ret;
            }
            return ret;
        };
        var newdata = [];
        if (arr instanceof Array) {
            for (var i = 0; i < arr.length; i++) {
                newdata[newdata.length] = arr[i];
            }
        } else {
            try {
                for (var key in arr) {
                    newdata.push(arr[key]);
                }
                ;
            } catch (e) {
            }
        }
        for (i = 0; i < newdata.length; i++) {
            var minIdx = i;
            var minData = (it !== '') ? newdata[i][it] : newdata[i];
            for (var j = i + 1; j < newdata.length; j++) {
                var tmpData = (it !== '') ? newdata[j][it] : newdata[j];
                var cmp = compareValues(minData, tmpData, dt, od);
                if (cmp < 0) {
                    minIdx = j;
                    minData = tmpData;
                }
            }
            if (minIdx > i) {
                var _child = newdata[minIdx];
                newdata[minIdx] = newdata[i];
                newdata[i] = _child;
            }
        }
        return newdata;
    }
}
swig.setFilter('inArray', function (arr, val) {
    val = val == undefined ? '' : val;
    return arr.indexOf(val.toString()) < 0 ? false : true;
});
swig.setFilter('layoutScore', function (arr) {
    var sum = 0;
    for (var i = 2; i < 6; i++) {
        sum += arr[i];
    }
    for (var i = 0; i < arr[6].length; i++) {
        sum += parseFloat(arr[6][i]);
    }
    return sum;
});
swig.setFilter('querBktRaceTrim', swigDefaults.querBktRaceTrim);
swig.setFilter('querBktRaceTrimStrict', swigDefaults.querBktRaceTrimStrict);
// 字符转数组
swig.setFilter('strForarr', function (val) {
    var arr = [];
    if (val != undefined) {
        for (var i = 0; i < val.length; i++) {
            var vlas = val[i];
            if (vlas == " ") {
                vlas = "&nbsp;";
            }
            arr.push(vlas);
        }
    }
    return arr;
});
// 字符串转数组
swig.setFilter('split', function (arr, str) {
    return arr.split(str);
});
// 反序
swig.setFilter('reverse', function (arr) {
    return arr.reverse();
});
swig.setFilter('DateComparison', function (now, old) {
    old = new Date(old * 1000);
    now = new Date(now * 1000);
    old = new Date(old.getFullYear() + "/" + (old.getMonth() + 1) + "/" + old.getDate());
    now = new Date(now.getFullYear() + "/" + (now.getMonth() + 1) + "/" + now.getDate());
    var rtData = {
        stat: false,
        date: now
    }
    if (now.getTime() > old.getTime()) {
        rtData.stat = true;
    }
    return rtData;
});
swig.setDefaults({locals: swigDefaults});
COMMONSTATIC = {
    RACE_TRIM: {
        BASKETBALL: {
            1: '未开赛',
            2: '第一节',
            3: '第一节完',
            4: '第二节',
            5: '第二节完',
            6: '第三节',
            7: '第三节完',
            8: '第四节',
            9: '加时',
            10: '已完赛',
            11: '中断',
            12: '取消',
            13: '延期',
            14: '腰斩',
            15: '待定',
            16: '加时'
        },
        FOOTBALL: {
            1: '未开赛',
            2: '第一节',
            3: '第一节完',
            4: '第二节',
            5: '第二节完',
            6: '第三节',
            7: '第三节完',
            8: '第四节',
            9: '加时',
            10: '已完赛',
            11: '中断',
            12: '取消',
            13: '延期',
            14: '腰斩',
            15: '待定',
            16: '加时'
        }
    },
    STATISTICAL: {
        BASKETBALL: {
            1: '3分球得分',
            2: '2分球得分',
            3: '罚球得分',
            4: '暂停',
            5: '犯规数',
            6: '罚球命中率%'
        }
    },
    WEEKS: ["日", "一", "二", "三", "四", "五", "六"],
    PLAYERSROLES: {
        BASKETBALL: {
            0: '未知',
            1: '教练',
            2: '前锋',
            3: '中锋',
            4: '后卫',
            5: 'SF小前锋',
            6: 'PF大前锋',
            7: 'SG得分后卫',
            8: 'PG组织后卫',
            9: 'C中锋'
        }
    }
};
